/**
 * 安全验证和配置管理模块
 */

const crypto = require('crypto');

class SecurityManager {
    constructor() {
        this.apiKeys = new Map();
        this.rateLimits = new Map();
        this.initializeSecurity();
    }

    /**
     * 初始化安全配置
     */
    initializeSecurity() {
        // 从环境变量加载API密钥
        this.loadAPIKeysFromEnv();
        
        // 设置默认的安全配置
        this.securityConfig = {
            maxRequestsPerMinute: 10,
            maxTokensPerRequest: 1000,
            allowedOrigins: ['http://localhost:8000', 'http://127.0.0.1:8000'],
            requireApiKey: process.env.NODE_ENV === 'production'
        };
    }

    /**
     * 从环境变量加载API密钥
     */
    loadAPIKeysFromEnv() {
        const keys = {
            openai: process.env.OPENAI_API_KEY,
            anthropic: process.env.ANTHROPIC_API_KEY,
            baidu: process.env.BAIDU_API_KEY
        };

        // 验证并存储API密钥
        Object.entries(keys).forEach(([provider, key]) => {
            if (key && key !== 'YOUR_API_KEY_HERE') {
                this.apiKeys.set(provider, key);
                console.log(`✅ ${provider.toUpperCase()} API密钥已配置`);
            } else {
                console.log(`⚠️ ${provider.toUpperCase()} API密钥未配置，相关功能将不可用`);
            }
        });
    }

    /**
     * 验证API密钥
     */
    validateAPIKey(apiKey, provider) {
        if (!this.securityConfig.requireApiKey) {
            return true; // 开发环境不强制要求API密钥
        }

        const expectedKey = this.apiKeys.get(provider);
        return expectedKey && apiKey === expectedKey;
    }

    /**
     * 检查速率限制
     */
    checkRateLimit(clientIP, endpoint) {
        const key = `${clientIP}:${endpoint}`;
        const now = Date.now();
        const windowMs = 60 * 1000; // 1分钟窗口

        if (!this.rateLimits.has(key)) {
            this.rateLimits.set(key, []);
        }

        const requests = this.rateLimits.get(key);
        
        // 清理过期的请求记录
        const validRequests = requests.filter(time => now - time < windowMs);
        this.rateLimits.set(key, validRequests);

        // 检查是否超过限制
        if (validRequests.length >= this.securityConfig.maxRequestsPerMinute) {
            return false;
        }

        // 记录当前请求
        validRequests.push(now);
        return true;
    }

    /**
     * 验证请求来源
     */
    validateOrigin(origin) {
        if (!origin) return true; // 允许没有origin的请求（如直接API调用）
        
        return this.securityConfig.allowedOrigins.some(allowedOrigin => 
            origin.startsWith(allowedOrigin)
        );
    }

    /**
     * 生成请求ID用于追踪
     */
    generateRequestId() {
        return crypto.randomBytes(8).toString('hex');
    }

    /**
     * 验证症状输入
     */
    validateSymptoms(symptoms) {
        if (!symptoms || typeof symptoms !== 'string') {
            return { valid: false, error: '症状描述必须为字符串' };
        }

        if (symptoms.trim().length === 0) {
            return { valid: false, error: '症状描述不能为空' };
        }

        if (symptoms.length > 1000) {
            return { valid: false, error: '症状描述过长（最大1000字符）' };
        }

        // 检查是否有恶意内容（简单过滤）
        const maliciousPatterns = [
            /<script[^>]*>/i,
            /javascript:/i,
            /on\w+\s*=/i,
            /eval\(/i
        ];

        for (const pattern of maliciousPatterns) {
            if (pattern.test(symptoms)) {
                return { valid: false, error: '输入包含不安全内容' };
            }
        }

        return { valid: true };
    }

    /**
     * 获取可用的模型列表
     */
    getAvailableModels() {
        const models = [
            { 
                id: 'openai', 
                name: 'OpenAI GPT', 
                available: this.apiKeys.has('openai'),
                maxTokens: 4000
            },
            { 
                id: 'claude', 
                name: 'Claude', 
                available: this.apiKeys.has('anthropic'),
                maxTokens: 4000
            },
            { 
                id: 'ernie', 
                name: '文心一言', 
                available: this.apiKeys.has('baidu'),
                maxTokens: 2000
            },
            { 
                id: 'local', 
                name: '本地模型', 
                available: true,
                maxTokens: 1000
            }
        ];

        return models;
    }

    /**
     * 记录安全事件
     */
    logSecurityEvent(eventType, details) {
        const timestamp = new Date().toISOString();
        console.log(`[SECURITY] ${timestamp} - ${eventType}:`, details);
    }
}

module.exports = SecurityManager;